package com.ujinsung.norebang
{
	import com.ujinsung.norebang.wordnet.WordNetProxy;
	import com.ujinsung.norebang.yahoo.newsfeeds.NewsFeedProxy;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	
	public class LyricsGenerator extends EventDispatcher
	{
		private var newsFeeds:NewsFeedProxy;
		private var wordNet:WordNetProxy;
		
		private var _nouns:Array;
		private var _numOfNouns:uint;
		private var _verbs:Array;
		private var _numOfVerbs:uint;
		
		private var searchCounter:uint;
		private var numOfSearch:uint;
		
		private var _titles:Array;
		private var _currentTitleNum:uint;
		
		public static var COMPLETE:String = "done";
		
		public function LyricsGenerator( numOfNoun:uint, numOfVerbs:uint )
		{
			_numOfNouns = numOfNoun;
			_numOfVerbs = numOfVerbs;
			numOfSearch=0;
			searchCounter = 0;
			_nouns = new Array();
			_verbs = new Array();
			newsFeeds = new NewsFeedProxy();
			newsFeeds.addEventListener( NewsFeedProxy.INIT, onNewsInit );
			wordNet = new WordNetProxy();
			wordNet.addEventListener( WordNetProxy.YES, onGetRightWord );
			wordNet.addEventListener( WordNetProxy.NO, noCount );
		}
		
		
		private function onNewsInit ( event:Event ):void {
			_titles = newsFeeds.titles;
			searchTitle ( _currentTitleNum );
		}
		
		private function searchTitle ( articleNum:uint ) :void{
			var title:String = _titles[articleNum];
			var words:Array = title.split(" ");
			for ( var j:uint = 0; j<words.length; j++) {
				// TODO: SORT OUT ONLY PROPER WORD.
				if ( words[j].toString().length > 2 ) {
					wordNet.search( words[j].toString() );
					numOfSearch++;
				}
			}
			_currentTitleNum++;
		}
		
		private function noCount ( event:Event ):void {
			searchCounter++;
			callComplete();
		}
		
		
		private function onGetRightWord ( event:Event ):void {
			
			searchCounter++;
			
			if ( WordNetProxy(event.target).wordObj.part == "noun" ) {
				_nouns.push( WordNetProxy(event.target).wordObj.word.toString() ) ;
			} else {
				_verbs.push( WordNetProxy(event.target).wordObj.word.toString() ) ;
			}
			callComplete();
		}
		
		private function callComplete () :void {
			if ( searchCounter >= numOfSearch ) {
				if ( _nouns.length >= _numOfNouns && this._verbs.length >= _numOfVerbs ) {
					dispatchEvent ( new Event ( COMPLETE ) );
				} else {
					searchTitle( _currentTitleNum );
				}
			}
		}
		
		public function getNouns(): Array {
			return _nouns; 
		}
		
		public function getVerbs():Array {
			return _verbs;
		}
	}
}